﻿using FastMvc.Auth;
using JQ.SAAS.DTO.SysPermissions;
using JQ.SAAS.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace JQ.SAAS.Service
{
    public class SysPermissionService : ISysPermissionService
    {
        private static List<PermissionDto> AllPermision;

        static SysPermissionService()
        {
            // 获取所有的Permission
            // 从代码的所有Controller以及Action中去获取

            var asms = System.AppDomain.CurrentDomain.GetAssemblies();
            AllPermision = new List<PermissionDto>();
            foreach (var asm in asms)
            {
                foreach (var t in asm.DefinedTypes)
                {
                    var tp = t.AsType();
                    var at = tp.GetCustomAttribute(typeof(PermissionCheckAttribute)) as PermissionCheckAttribute;
                    if (at != null)
                    {
                        PermissionDto pt = new PermissionDto() { Permission = at.Permission, pName = at.pName, pType = 0 };

                        foreach (var m in tp.GetMethods())
                        {
                            var ma = m.GetCustomAttribute(typeof(PermissionCheckAttribute)) as PermissionCheckAttribute;
                            if (ma != null && !pt.Childs.Any(t => t.Permission == at.Permission + "." + ma.Permission))
                            {
                                PermissionDto ct = new PermissionDto() { Permission = at.Permission + "." + ma.Permission, pName = ma.pName, pType = 1 };
                                pt.Childs.Add(ct);
                            }
                        }

                        if (at.CrudCreate)
                        {
                            pt.Childs.Add(new PermissionDto { Permission = at.Permission + ".create", pName = "创建", pType = 1 });
                        }
                        if (at.CrudUpdate)
                        {
                            pt.Childs.Add(new PermissionDto { Permission = at.Permission + ".create", pName = "修改", pType = 1 });
                        }
                        if (at.CrudDelete)
                        {
                            pt.Childs.Add(new PermissionDto { Permission = at.Permission + ".create", pName = "删除", pType = 1 });
                        }

                        AllPermision.Add(pt);
                    }
                }
            }
        }

        public async Task<List<PermissionDto>> GetAllPermisions() => await Task.FromResult(AllPermision);
    }
}
